package com.example.pcbcsmbackend.controller;

import com.example.pcbcsmbackend.entity.User;
import com.example.pcbcsmbackend.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/user")
@CrossOrigin(origins = "http://localhost:8080")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    // 用户注册
    @PostMapping("/register")
    public ResponseEntity<Map<String, Object>> register(@RequestBody Map<String, String> request) {
        Map<String, Object> response = new HashMap<>();
        try {
            String username = request.get("username");
            String password = request.get("password");
            String email = request.get("email");
            String phoneNumber = request.get("phoneNumber");
            
            User user = userService.register(username, password, email, phoneNumber);
            response.put("success", true);
            response.put("message", "注册成功");
            response.put("user", user);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    // 用户登录
    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> login(@RequestBody Map<String, String> request) {
        Map<String, Object> response = new HashMap<>();
        try {
            String username = request.get("username");
            String password = request.get("password");
            
            User user = userService.login(username, password);
            response.put("success", true);
            response.put("message", "登录成功");
            response.put("user", user);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    // 获取用户信息
    @GetMapping("/{userId}")
    public ResponseEntity<Map<String, Object>> getUserInfo(@PathVariable Integer userId) {
        Map<String, Object> response = new HashMap<>();
        Optional<User> user = userService.findById(userId);
        if (user.isPresent()) {
            response.put("success", true);
            response.put("user", user.get());
            return ResponseEntity.ok(response);
        } else {
            response.put("success", false);
            response.put("message", "用户不存在");
            return ResponseEntity.notFound().build();
        }
    }
    
    // 更新用户信息
    @PutMapping("/update/{userId}")
    public ResponseEntity<Map<String, Object>> updateUser(@PathVariable Integer userId, @RequestBody Map<String, Object> request) {
        Map<String, Object> response = new HashMap<>();
        try {
            String username = (String) request.get("username");
            String email = (String) request.get("email");
            String phoneNumber = (String) request.get("phoneNumber");
            Integer status = (Integer) request.get("status");
            
            User updatedUser = userService.updateUserInfo(userId, username, email, phoneNumber, status);
            response.put("success", true);
            response.put("message", "更新成功");
            response.put("user", updatedUser);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    // 创建用户（管理员功能）
    @PostMapping("/create")
    public ResponseEntity<Map<String, Object>> createUser(@RequestBody Map<String, Object> request) {
        Map<String, Object> response = new HashMap<>();
        try {
            String username = (String) request.get("username");
            String password = (String) request.get("password");
            String email = (String) request.get("email");
            String phoneNumber = (String) request.get("phoneNumber");
            Integer status = (Integer) request.get("status");
            
            User user = userService.createUser(username, password, email, phoneNumber, status);
            response.put("success", true);
            response.put("message", "用户创建成功");
            response.put("user", user);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    // 删除用户（管理员功能）
    @DeleteMapping("/{userId}")
    public ResponseEntity<Map<String, Object>> deleteUser(@PathVariable Integer userId) {
        Map<String, Object> response = new HashMap<>();
        try {
            userService.deleteUser(userId);
            response.put("success", true);
            response.put("message", "用户删除成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    // 获取所有用户（管理员功能）
    @GetMapping("/all")
    public ResponseEntity<Map<String, Object>> getAllUsers() {
        Map<String, Object> response = new HashMap<>();
        List<User> users = userService.getAllUsers();
        response.put("success", true);
        response.put("users", users);
        return ResponseEntity.ok(response);
    }
    
    // 更新用户状态（管理员功能）
    @PutMapping("/status")
    public ResponseEntity<Map<String, Object>> updateUserStatus(@RequestBody Map<String, Object> payload) {
        Map<String, Object> response = new HashMap<>();
        try {
            Integer userId = (Integer) payload.get("userId");
            Integer status = (Integer) payload.get("status");
            userService.updateUserStatus(userId, status);
            response.put("success", true);
            response.put("message", "状态更新成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 批量更新用户状态
    @PutMapping("/batch/status")
    public ResponseEntity<Map<String, Object>> batchUpdateUserStatus(@RequestBody Map<String, Object> payload) {
        Map<String, Object> response = new HashMap<>();
        try {
            List<Integer> userIds = (List<Integer>) payload.get("userIds");
            Integer status = (Integer) payload.get("status");
            userService.batchUpdateUserStatus(userIds, status);
            response.put("success", true);
            response.put("message", "批量更新用户状态成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "批量更新失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 批量删除用户
    @DeleteMapping("/batch")
    public ResponseEntity<Map<String, Object>> batchDeleteUsers(@RequestBody Map<String, Object> payload) {
        Map<String, Object> response = new HashMap<>();
        try {
            List<Integer> userIds = (List<Integer>) payload.get("userIds");
            userService.batchDeleteUsers(userIds);
            response.put("success", true);
            response.put("message", "批量删除用户成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "批量删除失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
} 